//
//  LXNavigationController.swift
//  LXTXShop
//
//  Created by apple on 2018/4/3.
//  Copyright © 2018年 LX. All rights reserved.
//

import UIKit

func T_Window() -> UIWindow {return UIApplication.shared.keyWindow!}

func T_WindowView() -> UIView {
    
    if var windowView = UIApplication.shared.keyWindow?.rootViewController?.view {
        let ctrl = UIApplication.shared.keyWindow?.rootViewController;
        while (true) {
            if ((ctrl?.presentedViewController) != nil) {
                windowView = (ctrl?.presentedViewController?.view)!;
            }
            break
        }
        return windowView
    }else {
        return UIView()
    }
}

func width() -> CGFloat { return UIScreen.main.bounds.size.width}
func height() -> CGFloat { return UIScreen.main.bounds.size.height}
let TOUCH_DISTANCE: CGFloat = 80

enum PopAnimationType {
    case popAnimationTypeFromeBehind , popAnimationTypeliner
}

class LXNavigationController: UINavigationController,UINavigationControllerDelegate,UIGestureRecognizerDelegate {

    internal var popAnimationType:PopAnimationType?
    internal var canDragBack:Bool?   // 是否能拖拽
    
    var snapArray: NSMutableArray?
    var startPoint: CGPoint?
    var backgroundView: UIView?
    var blackMask: UIView? //这个视图的作用是使切换的时候更加顺畅
    var lastScreenShotImageView: UIImageView?
    var isMoving: Bool?
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        snapArray = NSMutableArray()
        canDragBack = true
    }
    
    override init(rootViewController: UIViewController) {
        super.init(rootViewController: rootViewController)
        snapArray = NSMutableArray()
        canDragBack = true
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        snapArray = NSMutableArray()
        canDragBack = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.interactivePopGestureRecognizer?.isEnabled = false
        let panRecognizer = UIPanGestureRecognizer.init(target: self, action: #selector(didPanGestureRecognizer(_:)))
        panRecognizer.delegate = self
        self.view.addGestureRecognizer(panRecognizer)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        if snapArray?.count == 0 {
            if let captureImage = capture() {
                self.snapArray?.add(captureImage)
            }
        }
    }
    
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        if self.viewControllers.count >= 1 {
            let btn = UIButton(frame:CGRect(x: 0, y: 0, width: 25, height: 25))
            btn.setBackgroundImage(UIImage(named: "lx_common_nav_back"), for: UIControlState())
            btn.addTarget(self, action: #selector(actionBack), for: UIControlEvents.touchUpInside)
            let leftBtn  = UIBarButtonItem(customView:btn)
            viewController.navigationItem.leftBarButtonItem = leftBtn
        }
        
        if let captureImage = capture() {
            self.snapArray?.add(captureImage)
        }
        if self.viewControllers.count >= 1{
            viewController.hidesBottomBarWhenPushed = true
        }
        super.pushViewController(viewController, animated: animated)
    }
    
    override func popViewController(animated: Bool) -> UIViewController? {
        self.snapArray?.removeLastObject()
        return super.popViewController(animated: animated)
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        
        //        if gestureRecognizer.isKind(of: UIPanGestureRecognizer.classForCoder()){
        //            if self.topViewController != nil{
        //                    let tPoint = (gestureRecognizer as! UIPanGestureRecognizer).translation(in: gestureRecognizer.view)
        //                    if tPoint.x >= 0{
        //                        let y = fabs(tPoint.y)
        //                        let x = fabs(tPoint.x)
        //                        let af = 30.0/180.0*M_PI
        //                        let tf = tanf(Float(af))
        //                        if (y/x) <= CGFloat(tf){
        //                            return true
        //                        }
        //                        return false
        //                    }else{
        //                        return false
        //                    }
        //            }
        //        }
        //        return true
        
        
        if NSStringFromClass((touch.view?.classForCoder)!) == "UITableViewCellContentView"{
            return false
        }else{
            if (self.viewControllers.count <= 1 || self.canDragBack == false) {
                return false
            }
            //            else{
            //                XLog("-----==>\(NSStringFromClass((self.viewControllers.last?.classForCoder)!))")
            //                if NSStringFromClass((self.viewControllers.last?.classForCoder)!) == "FXZB2BShopSwift.FXProductListVC" {
            //                    return false
            //                }
            //            }
            return true
        }
    }
    
    
    @objc func didPanGestureRecognizer(_ pan: UIPanGestureRecognizer) {
        if (self.viewControllers.count <= 1 || self.canDragBack == false){
            return
        }
        
        let touchPoint = pan.location(in: T_Window())
        if pan.state == .began {//手势开始
            self.startPoint = touchPoint
            self.isMoving = true
            addSnapView()
        } else if(pan.state == .ended){//手势结束
            if (CGFloat(touchPoint.x - self.startPoint!.x) > TOUCH_DISTANCE) {
                UIView.animate(withDuration: 0.3, animations: {
                    self.doMoveViewWithX(width())
                }, completion: { finished in
                    self.isMoving = false
                    self.popViewController(animated: false)
                    var frame = T_WindowView().frame
                    frame.origin.x = 0
                    T_WindowView().frame = frame
                })
            }else{
                UIView.animate(withDuration: 0.3, animations: {
                    self.doMoveViewWithX(0)
                }, completion: { finished in
                    self.isMoving = false
                    self.backgroundView?.isHidden = true
                })
            }
            return
        }else if(pan.state == .cancelled){
            UIView.animate(withDuration: 0.3, animations: {
                self.doMoveViewWithX(0)
            }, completion: { finished in
                self.isMoving = false
                self.backgroundView?.isHidden = true
            })
            return
        }
        
        if self.isMoving == true {
            self.doMoveViewWithX(CGFloat(touchPoint.x - self.startPoint!.x))
        }
    }
    
    func addSnapView(){
        self.backgroundView?.removeFromSuperview()
        //        if self.backgroundView == nil {
        self.backgroundView = UIView.init(frame: self.view.bounds)
        self.backgroundView?.backgroundColor = .yellow
        T_WindowView().superview?.insertSubview(self.backgroundView!, belowSubview: T_WindowView())
        self.blackMask = UIView.init(frame: CGRect(x: 0, y: 0, width: width() , height: height()))
        self.blackMask?.backgroundColor = .black
        self.backgroundView?.addSubview(self.blackMask!)
        //        }
        
        self.backgroundView?.isHidden = false
        if self.lastScreenShotImageView != nil {
            self.lastScreenShotImageView?.removeFromSuperview()
        }
        
        let lastScreenShot = self.snapArray?.lastObject as? UIImage
        self.lastScreenShotImageView = UIImageView(image: lastScreenShot)
        self.lastScreenShotImageView?.frame = CGRect(x: 0, y: 0, width: width(),height: height())
        self.backgroundView?.insertSubview(self.lastScreenShotImageView!, belowSubview: self.blackMask!)
    }
    
    
    func doMoveViewWithX(_ x:CGFloat){
        var x = x
        x = x > width() ? width():x
        x = x < 0 ? 0 : x
        var frame = T_WindowView().frame
        frame.origin.x = x
        T_WindowView().frame = frame
        
        animationFromBehind(x) // 3D
        //        animationLiner(x)  // 线性
    }
    
    func animationFromBehind(_ x: CGFloat){
        //        let coeffiient = width() * 25
        //        let scale = (x/coeffiient) + 0.96
        //        let alpha = 0.4 - (x/800)
        //        self.lastScreenShotImageView?.transform = CGAffineTransform(scaleX: scale, y: scale)
        //        self.blackMask?.alpha = alpha
        //之前的滑动动作是有黑边的，不需要这种效果，取消by li
        self.lastScreenShotImageView?.transform = CGAffineTransform(scaleX: 1, y: 1)
        self.blackMask?.alpha = 0
    }
    
    func animationLiner(_ x: CGFloat){
        let coefficient = x / 2
        var screenShotImageViewFrame = self.lastScreenShotImageView?.frame
        screenShotImageViewFrame?.origin.x = -width()/2 + coefficient
        self.lastScreenShotImageView?.frame = screenShotImageViewFrame!
        self.blackMask?.alpha = 0.3
    }
    
    /**
     截屏
     
     - returns: 截屏图片
     */
    func capture() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(CGSize(width: T_WindowView().frame.width, height: T_WindowView().frame.height), T_WindowView().isOpaque, 0.0)
        
        if let currentCtx = UIGraphicsGetCurrentContext() {
            T_WindowView().layer.render(in: currentCtx)
        }
        
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
    
    deinit {
        self.snapArray = nil
        self.backgroundView?.removeFromSuperview()
        self.backgroundView = nil
    }
    
    //返回按钮事件
    
    @objc func actionBack(){
        //        self.snapArray?.removeLastObject()
        //        super.popViewController(animated: true)
        addSnapView()
        UIView.animate(withDuration: 0.3, animations: {
            self.doMoveViewWithX(width())
        }, completion: { finished in
            self.isMoving = false
            self.popViewController(animated: false)
            var frame = T_WindowView().frame
            frame.origin.x = 0
            T_WindowView().frame = frame
        })
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
